package com.wanhe.base.runner;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

/**
 * Created by yangchaoxun on 2016/11/17.
 */
public class MainTaskExecutor implements ThreadExecutor {

    private static final int INITIAL_POOL_SIZE =3;
    private static final int MAX_POOL_SIZE=7;

    private static final int KEEP_ALIVE_TIME = 10;
    private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;

    private final BlockingQueue<Runnable> myWorkQueue;
    private final ThreadPoolExecutor threadPoolExecutor;
    private final ThreadFactory threadFactory;

    @Inject
    public MainTaskExecutor(){
        this.myWorkQueue = new LinkedBlockingQueue<>();
        this.threadFactory = new TaskThreadFactory();
        this.threadPoolExecutor = new ThreadPoolExecutor(INITIAL_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT,
                this.myWorkQueue, this.threadFactory);

    }

    @Override
    public void execute(Runnable command) {
        if(command==null){
            throw new IllegalArgumentException("Runnable to execute cannot be null");
        }
        this.threadPoolExecutor.execute(command);
    }


    private static class TaskThreadFactory implements ThreadFactory {

        private static final String THREAD_NAME = "wanheMenu_";
        private int counter =0;

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, THREAD_NAME+counter++);
        }
    }


}
